#include "treegen3d.h"
#include "math.h"
#include "3DAlgo/shadow3d.h"
#include "common.h"
using namespace std;

TreeGen3D::TreeGen3D() : TreeGen()
{
}

void TreeGen3D::genTree(){
    treeRoot->start = float3(200,5,200);
    treeRoot->end = float3(200,20,200);
    treeRoot->aux = NULL;
    treeRoot->term = NULL;
    treeRoot->theta = 0;
    treeRoot->phi = 0;
    treeRoot->diameter = 1;
    treeRoot->direction = float3(0,1,0);
    initializeBud(treeRoot);
}

void TreeGen3D::stupidGen(Bud *b, int depth){
    if(depth <2){
        b->aux = new Bud();
        createBudFromBud(b, b->aux);
        cout<<b->end<<endl;

        b->aux->end = b->auxDir*6 + b->aux->start;
        cout<<b->aux->end<<endl;
        b->aux->diameter = 1;
        initializeBud(b->aux);

//        b->term = new Bud();
//        createBudFromBud(b,b->term);
//        b->term->end = b->direction*6 + b->end;
//        b->term->diameter = 1;
//        initializeBud(b->term);

        stupidGen(b->aux, depth +1);
//        stupidGen(b->term, depth +1);
    }
}

void TreeGen3D::initializeBud(Bud *b){
    float3 dir(b->end.x - b->start.x, b->end.y - b->start.y, b->end.z - b->start.z);
    b->length = dir.getMagnitude();
    dir.normalize();

    //double r = sqrt(dir.x*dir.x + dir.y*dir.y + dir.z*dir.z);
    b->theta = atan2(-dir.z, dir.x);
    b->phi = acos(dir.y);


    b->direction = dir;

    double ttheta = (rand() % 100 /100.0) * 2.0*PI;
    //random direction with aux angle about y-axis
    float3 adir(sin(AUX_ANGLE)*cos(ttheta),
                cos(AUX_ANGLE),
                sin(AUX_ANGLE)*sin(ttheta));
    //now rotate using phi and theta of direction:
    double xp = adir.x * cos(b->phi) - adir.y * sin(b->phi);
    double yp = adir.x * sin(b->phi) + adir.y * cos(b->phi);
    double zp = adir.z;
    adir.x = zp*sin(b->theta) + xp * cos(b->theta);
    adir.y = yp;
    adir.z = zp * cos(b->theta) - xp*sin(b->theta);

    b->auxDir = adir;


    b->darken = max((double)(rand()%100) /100.0, 0.7);

}
